// FC表示函数组件
// 之前在react解构现在还在react解构
import { FC, useState, useEffect, useMemo, ChangeEvent } from 'react';

// tsx的后缀只能省略
import Child from './components/Child';

// 用interface来定义对象的类型
interface ItemType {
  name: string;
  id: number;
}

const Index: FC = () => {
  // useState的变量的类型要用泛型的方式加
  // const [count, setCount] = useState<number | string>(0);
  const [count, setCount] = useState<number>(0);

  // 函数要加返回值的类型
  const fn = (): void => {
    setCount((v) => v + 1);
  };

  // useEffect不需要加类型
  useEffect(() => {
    setCount(3);
  }, []);

  // useMemo的类型要用泛型的方式加
  const doubleCount = useMemo<number>(() => {
    return count * 2;
  }, [count]);

  const [value, setValue] = useState<string>('');
  const [list, setList] = useState<ItemType[]>([
    {
      id: 1,
      name: 'zhangsan',
    },
    {
      id: 2,
      name: 'lisi',
    },
  ]);

  const fn2 = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  const add = (): void => {
    setList((v) => [...v, { id: new Date().getTime(), name: value }]);
  };

  // 函数参数的类型都是要写的
  const remove = (id: number): void => {
    setList((v) => v.filter((item) => item.id !== id));
  };

  return (
    <>
      <h2>ts页面</h2>
      <span>{count}</span>
      <button onClick={fn}>+</button>
      <p>doubleCount: {doubleCount}</p>

      <hr />

      <input type="text" value={value} onChange={fn2} />
      <button onClick={add}>添加</button>
      <ul>
        {list.map((item) => (
          <li key={item.id}>
            {item.name} - <button onClick={() => remove(item.id)}>删除</button>
          </li>
        ))}
      </ul>

      <hr />

      <Child count={count} />
    </>
  );
};

export default Index;
